package com.b2c.erp.controller;

import com.b2c.entity.DataRow;
import com.b2c.entity.erp.enums.InvoiceBillStatusEnum;
import com.b2c.entity.erp.vo.InvoiceInfoListVo;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.vo.wms.InvoiceDetailVo;
import com.b2c.entity.enums.EnumUserActionType;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.vo.ErpPurchaseStockInItemVo;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.interfaces.wms.InvoiceService;
import com.b2c.interfaces.wms.StockInService;
import com.b2c.interfaces.wms.StockLocationService;
import com.b2c.erp.req.ErpCheckoutStockInReq;
import com.b2c.erp.req.ErpPurchaseStockInReq;
import com.b2c.erp.response.ApiResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 描述：
 * 商品入库
 *
 * @author qlp
 * @date 2019-05-30 17:19
 */
@RequestMapping(value = "/ajax_stock_in")
@RestController
public class AjaxStockInController {
    @Autowired
    private StockLocationService stockLocationService;
    @Autowired
    private InvoiceService invoiceService;
    @Autowired
    private StockInService stockInService;
    @Autowired
    private ErpUserActionLogService logService;
    private static Logger log = LoggerFactory.getLogger(AjaxStockInController.class);
    /**
     * 根据商品sku编码获取商品规格信息
     *
     * @param request
     * @return
     */
//    @RequestMapping(value = "/goods_spec_by_iid_and_number", method = RequestMethod.POST)
//    public ApiResult<PurchaseStockInAjaxResponse> getGoodsSpecDetail(@RequestBody GoodsSpecInReq request) {
//
//        //查询商品
//        InvoiceInfoListVo vo = invoiceService.getGoodsSpecByInvoiceAndSpec(request.getInvoiceId(), request.getSpecNumber());
//        if (vo == null) return new ApiResult<>(404, "采购单中没有该商品");
//
//        var goodsSpec = goodsService.getGoodsSpecDetailByNumber(request.getSpecNumber());
//        if (goodsSpec == null) return new ApiResult<>(403, "商品不存在");
//
//        PurchaseStockInAjaxResponse response = new PurchaseStockInAjaxResponse();
//        response.setInvoiceId(request.getInvoiceId());
//        response.setInvoiceInfoId(vo.getId());
//        response.setGoodsId(goodsSpec.getGoodsId());
//        response.setSpecId(goodsSpec.getSpecId());
//        response.setGoodsNumber(goodsSpec.getGoodsNumber());
//        response.setGoodsName(goodsSpec.getGoodsName());
//        response.setColorValue(goodsSpec.getColorValue());
//        response.setSizeValue(goodsSpec.getSizeValue());
//        response.setStyleValue(goodsSpec.getStyleValue());
//        response.setSpecNumber(goodsSpec.getSpecNumber());
//        response.setQualifiedQuantity(vo.getQualifiedQuantity());
//        response.setInQuantity(vo.getInQuantity());
//
//
//        return new ApiResult<>(0, "SUCCESS", response);
//    }

    /**
     * 商品入库 数据校验
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/checkout_stock_in_data_checked", method = RequestMethod.POST)
    public ApiResult<Integer> stockIn(@RequestBody ErpCheckoutStockInReq req, HttpServletRequest request) {
        if (req.getCheckoutId() == null || req.getCheckoutId().longValue() <= 0) {
            return new ApiResult<>(500, "参数错误，缺少checkoutId");
        }

//        HttpSession session = request.getSession();
//        Object userid = session.getAttribute("userId");
//        String userName = (String) session.getAttribute("userName");

//        var result = stockInService.checkoutStockIn(request.getCheckoutId(),request.getItems(), (int) userid, userName);
        var result = stockInService.checkoutStockInDataChecked(req.getCheckoutId(), req.getItems());


        if (result.getCode() == 0) {
            return new ApiResult<>(0, "SUCCESS");
        } else {
            return new ApiResult<>(result.getCode(), result.getMsg());
        }

//        if (result == -404) {
//            //表单数据错误
//            return new ApiResult<>(404, "表单不存在");
//        } else if (result == -505) {
//            //表单数据错误 ,itemid不存在
//            return new ApiResult<>(404, "参数错误，itemId不在范围内");
//        }else if (result == -1) {
//            //入库数量已满
//            return new ApiResult<>(405, "该商品已入库完成");
//        } else if (result == -2) {
//            //入库数量已满
//            return new ApiResult<>(406, "该仓位已经被占用了");
//        }
//
//        return new ApiResult<>(0, "SUCCESS");
    }


    /**
     * 商品入库 数据校验
     *
     * @param req
     * @return
     */
    @RequestMapping(value = "/purchase_stock_in_data_checked", method = RequestMethod.POST)
    public ApiResult<Integer> purchaseStockInCheck(@RequestBody ErpPurchaseStockInReq req, HttpServletRequest request) {
        if (req.getInvoiceId() == null || req.getInvoiceId().longValue() <= 0) {
            return new ApiResult<>(500, "参数错误，缺少checkoutId");
        }

//        HttpSession session = request.getSession();
//        Object userid = session.getAttribute("userId");
//        String userName = (String) session.getAttribute("userName");

//        var result = stockInService.checkoutStockIn(request.getCheckoutId(),request.getItems(), (int) userid, userName);
        var result = stockInService.purchaseStockInDataChecked(req.getInvoiceId(), req.getItems());


        if (result.getCode() == 0) {
            return new ApiResult<>(0, "SUCCESS");
        } else {
            return new ApiResult<>(result.getCode(), result.getMsg());
        }

//        if (result == -404) {
//            //表单数据错误
//            return new ApiResult<>(404, "表单不存在");
//        } else if (result == -505) {
//            //表单数据错误 ,itemid不存在
//            return new ApiResult<>(404, "参数错误，itemId不在范围内");
//        }else if (result == -1) {
//            //入库数量已满
//            return new ApiResult<>(405, "该商品已入库完成");
//        } else if (result == -2) {
//            //入库数量已满
//            return new ApiResult<>(406, "该仓位已经被占用了");
//        }
//
//        return new ApiResult<>(0, "SUCCESS");
    }

    /**
     * 入库提交AJAX（2021-07-22）
     * @param request
     * @return
     */
    @RequestMapping(value = "/purchase_stock_in_data", method = RequestMethod.POST)
    public ApiResult<Integer> purchase_stock_in_data(HttpServletRequest request) {
        Long invoiceId = Long.parseLong(request.getParameter("invoiceId"));
        Integer qcReport = Integer.parseInt(request.getParameter("qcReport"));
        String qcInspector = request.getParameter("qcInspector");

        log.info("入库操作，ID:"+invoiceId);

        //查询入库单
        var invoice = invoiceService.getInvoiceDetail(invoiceId);
        if (invoice == null) {
            return new ApiResult<>(EnumResultVo.Fail.getIndex(),"没有找到数据");
        }
        if(invoice.getBillStatus().intValue() != InvoiceBillStatusEnum.Audited.getIndex()){
            return new ApiResult<>(EnumResultVo.Fail.getIndex(),"该表单状态不是已审核状态");
        }

        /***组合入库items***/
        String[] specIdArr = request.getParameterValues("specId");
        String[] specNumberArr = request.getParameterValues("specNumber");
        String[] goodsNumberArr = request.getParameterValues("goodsNumber");
        String[] itemIdArr = request.getParameterValues("infoId");
        String[] locationIdArr = request.getParameterValues("locationId");
        String[] priceArr = request.getParameterValues("price");//商品采购价
        //String[] locationNumberArr = request.getParameterValues("locationNumber");
        String[] quantityArr = request.getParameterValues("quantity");
        String[] maxQuantityArr = request.getParameterValues("maxQuantity");


        List<ErpPurchaseStockInItemVo> items = new ArrayList<>();
        for (int i = 0; i < specIdArr.length; i++) {
            if(StringUtils.isEmpty(locationIdArr[i]) || locationIdArr[i].equals("0"))return new ApiResult<>(EnumResultVo.Fail.getIndex(),specNumberArr[i]+",未选择仓位");
            if (StringUtils.isEmpty(quantityArr[i]) == false) {
                if(Integer.parseInt(quantityArr[i])>Integer.parseInt(maxQuantityArr[i])) return new ApiResult<>(EnumResultVo.Fail.getIndex(),specNumberArr[i]+"入库数量超过最大可入库数量");
                ErpPurchaseStockInItemVo item = new ErpPurchaseStockInItemVo();
                item.setSpecId(Integer.parseInt(specIdArr[i]));
                item.setSpecNumber(specNumberArr[i]);
                item.setLocationId(Integer.parseInt(locationIdArr[i]));
                item.setPrice(Double.parseDouble(priceArr[i]));
                item.setGoodsNumber(goodsNumberArr[i]);
                //item.setLocationNumber(locationNumberArr[i]);
                item.setQuantity(Long.parseLong(quantityArr[i]));
                item.setInvoiceInfoId(Long.parseLong(itemIdArr[i]));
                items.add(item);
            }
        }
        var result = stockInService.purchaseStockIn(invoiceId, qcReport, qcInspector, items, DataConfigObject.getInstance().getLoginUserId(), DataConfigObject.getInstance().getLoginUserName());

        //添加系统日志
        logService.addUserAction(DataConfigObject.getInstance().getLoginUserId(), EnumUserActionType.Add,
                "/purchase/stock_in", "采购入库 , id : " + invoiceId + " , 日期 : " + new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss").format(new Date()), "成功");

        return new ApiResult<>(result.getCode(),result.getMsg());
    }

    /**
     * 根据仓库ID获取库区信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/get_reservoir_by_locationId", method = RequestMethod.POST)
    public ApiResult<List> getReservoir(@RequestBody Object id) {
//        List<ReservoirEntity> list = reservoirService.getIdByHouseId((int) id);
        var list = stockLocationService.getListByParentId((int) id);
        return new ApiResult<>(0, "SUCCESS", list);
    }

    /**
     * 根据库区ID获取货架信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/get_shelf_by_reservoirId", method = RequestMethod.POST)
    public ApiResult<List> getShelf(@RequestBody Object id) {

        var list = stockLocationService.getListByParentId((int) id);
//        var list = stockLocationService.getShelfByReservoirIdAndNotUsed();
//        List<ErpStockLocationBatchAddVo> list = shelfService.getShelfByReservoirId((int) id);
        return new ApiResult<>(0, "SUCCESS", list);
    }

    /**
     * 检验弹窗
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST)
    public ApiResult<InvoiceDetailVo> getCheckout(@RequestBody DataRow data) {
        var detail = invoiceService.getInvoiceDetail(Long.valueOf(data.getString("id")));
        List<InvoiceInfoListVo> items = detail.getItems();
        for (InvoiceInfoListVo vo : items) {
            if (vo.getLocationId() != null) {

                String locationName = stockLocationService.getName(vo.getLocationId());
                vo.setLocationName(locationName);
//                String reservoirName = invoiceService.getReservoirName(vo.getReservoirId());
//                vo.setReservoirName(reservoirName);
//                String shelfName = invoiceService.getShelfName(vo.getShelfId());
//                vo.setShelfName(shelfName);
            }
        }
        return new ApiResult<>(0, "SUCESS检验弹窗", detail);
    }

}
